package cn.yogehaoren.utils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.Reader;

/**
 * @author WangNing yogehaoren@gamil.com <br>
 * @since 1.0
 */
public class SqlSessionManager {

    private static SqlSessionFactory sqlSessionFactory;

    public static SqlSession getSqlSession(){
        if(sqlSessionFactory == null){
            synchronized (SqlSessionManager.class){
                if(sqlSessionFactory != null){
                    return sqlSessionFactory.openSession();
                }else {

                    try {
                        Reader reader = Resources.getResourceAsReader("mybatis-config.xml");
                        sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
                        reader.close();
                        return sqlSessionFactory.openSession();
                    } catch (IOException e) {
                        e.printStackTrace();
                        return null;
                    }

                }
            }
        }
        return sqlSessionFactory.openSession();
    }

    public static  <T> T getMapper(SqlSession sqlSession, Class<T> clazz){
        if(sqlSession == null){
            return null;
        }

        return sqlSession.getMapper(clazz);

    }

}
